package com.atguigu.yygh.msm.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.msm.service.MsmService;
import com.atguigu.yygh.msm.utils.HttpUtils;
import com.atguigu.yygh.vo.msm.MsmVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 孔德成
 * @slogan 致敬大师，致敬未来的你
 * @date 2021/9/8 10:36 上午
 * @desc
 */
@Service
@Slf4j
public class MsmServiceImpl implements MsmService {

    private final RedisTemplate<String, String> redisTemplate;

    public MsmServiceImpl(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    @Override
    public void send(String phone) {
        // 1. 查询redis数据库中是否存在验证码，防止用户非正常发送验证码
        String s = redisTemplate.opsForValue().get(phone);
        if (StrUtil.isNotBlank(s)) {
            return;
        }
        // 2. 发送验证码
        String code = RandomUtil.randomNumbers(4);
        sendMsmCode(phone, code);
        // 3. 将验证码缓存到redis中，并设置过期时间
        redisTemplate.opsForValue().set(phone, code, 120, TimeUnit.SECONDS);
    }

    //发送短信实现
    @Override
    public boolean sendMq(MsmVo msmVo) {
        // 1. 判断手机号是否为空
        if (StrUtil.isBlank(msmVo.getPhone())) {
            return false;
        }
        // 2. 根据短信模板发送短息 mktodo 申请短信模板
        String templateCode = msmVo.getTemplateCode();
        if ("预约下单".equals(templateCode)) {
            log.info("恭喜 {} 预约成功", msmVo.getPhone());
        } else if ("验证码".equals(templateCode)) {
            String code = RandomUtil.randomNumbers(4);
            log.info("手机号：{}, 验证码：{}, 有效时间2分钟", msmVo.getPhone(), code);
        } else if ("就诊提醒".equals(templateCode)) {
            Map<String, Object> param = msmVo.getParam();
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(param));
            String title = jsonObject.getString("title");
            String reserveDate = jsonObject.getString("reserveDate");
            String name = jsonObject.getString("name");
            log.info("title: {}, reserveDate: {}, name: {}", title, reserveDate, name);
        } else {
            return false;
        }
        return true;
    }

    /**
     * 发送短信验证码
     *
     * @param phone 手机号
     * @param code  验证码
     */
    private void sendMsmCode(String phone, String code) {


        String host = "https://gyytz.market.alicloudapi.com";
        String path = "/sms/smsSend";
        String method = "POST";
        String appcode = "db7df8ccb15e4bf98072981ee5f56678";
        // 请求头
        Map<String, String> headers = new HashMap<>(1);
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        // 请求参数
        Map<String, String> querys = new HashMap<>(4);
        querys.put("mobile", phone);
        String param = String.format("**code**:%s,**minute**:%d", code, 2);
        log.info(param);
        querys.put("param", param);
        // 测试签名
        querys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
        // 测试模版
        // 短信内容为 { 验证码：**code**，**minute**分钟内有效，请勿泄漏于他人！}）
        querys.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");
        Map<String, String> bodys = new HashMap<>();
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            log.info(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new YyghException(20001, "发送失败");
        }
    }
}
